// stores/tagStore.ts
import { defineStore } from 'pinia';
import { useRouter } from 'vue-router';
import { computed, ref } from 'vue';
import type { StoredState, TagItem } from '../interface/index';

export const useTagStore = defineStore('tag', () => {
  const router = useRouter();

  // 安全初始化状态
  const initState = (): StoredState => {
    try {
      const saved = localStorage.getItem('tag-navigation');
      if (saved) {
        const parsed = JSON.parse(saved) as StoredState;
        // 验证数据格式
        if (
          Array.isArray(parsed?.tags) &&
          typeof parsed?.activeIndex === 'number'
        ) {
          return {
            tags:
              parsed.tags.length > 0
                ? parsed.tags
                : [{ title: '首页', path: '/' }],
            activeIndex: Math.max(
              0,
              Math.min(parsed.activeIndex, parsed.tags.length - 1),
            ),
          };
        }
      }
    } catch (e) {
      console.error('Failed to parse saved tags', e);
    }
    return { tags: [{ title: '首页', path: '/' }], activeIndex: 0 };
  };

  // 使用 reactive 替代 ref 确保嵌套属性响应性
  const state = ref<StoredState>(initState());

  // 安全的计算属性
  const tags = computed(() => state.value.tags || []);
  const activeIndex = computed({
    /**当左侧的值为 null 或 undefined 时，返回右侧的默认值 0
   只有左侧为 null 或 undefined 时才会触发默认值（与 || 不同） */
    get: () => state.value.activeIndex ?? 0,
    set: (val) => {
      state.value.activeIndex = Math.max(
        0,
        Math.min(val, tags.value.length - 1),
      );
      saveState();
    },
  });

  // 保存状态（添加防错处理）
  const saveState = () => {
    try {
      localStorage.setItem(
        'tag-navigation',
        JSON.stringify({
          tags: tags.value,
          activeIndex: activeIndex.value,
        }),
      );
    } catch (e) {
      console.error('Failed to save tags', e);
    }
  };

  // 安全的添加标签方法
  const addTag = (tag: TagItem) => {
    if (!tag?.path) return;

    const currentTags = tags.value;
    const existsIndex = currentTags.findIndex((t) => t.path === tag.path);

    if (existsIndex === -1) {
      state.value.tags = [...currentTags, tag];
      setActive(currentTags.length); // 激活新添加的标签
    } else {
      setActive(existsIndex);
    }
  };

  // 设置活动标签（带边界检查）
  const setActive = (index: number) => {
    const validIndex = Math.max(0, Math.min(index, tags.value.length - 1));
    activeIndex.value = validIndex;

    // 只有当路径不同时才跳转
    if (router.currentRoute.value.path !== tags.value[validIndex].path) {
      router.push(tags.value[validIndex].path);
    }
  };

  // 删除标签（带安全检查）
  const removeTag = (index: number) => {
    const currentTags = tags.value;
    if (index < 0 || index >= currentTags.length) return;

    const wasActive = activeIndex.value === index;
    state.value.tags = currentTags.filter((_, i) => i !== index);

    if (wasActive) {
      const newIndex = Math.max(0, Math.min(index - 1, currentTags.length - 2));
      if (tags.value[newIndex]) {
        router.push(tags.value[newIndex].path);
      } else {
        router.push('/');
      }
    }

    // 自动调整 activeIndex（通过 computed setter）
    if (index <= activeIndex.value) {
      activeIndex.value = Math.max(0, activeIndex.value - 1);
    }
    saveState();
  };

  return {
    tags,
    activeIndex,
    addTag,
    removeTag,
    setActive,
  };
});
